<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .navbar-brand {
            font-weight: bold;
        }
        .table-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            padding: 20px;
        }
        .action-buttons .btn {
            margin-right: 5px;
        }
        .modal-header {
            background-color: #0d6efd;
            color: white;
        }
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #6c757d;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        .search-box {
            max-width: 300px;
        }
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #dee2e6;
        }
        .btn-edit {
            background-color: #0dcaf0;
            border-color: #0dcaf0;
            color: white;
        }
        .btn-edit:hover {
            background-color: #31d2f2;
            border-color: #25cff2;
            color: white;
        }
        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
        }
        .stats-card {
            border-left: 4px solid #0d6efd;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">数据库与Web开发基础</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/users">用户管理</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container my-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>用户管理系统</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="bi bi-plus-circle"></i> 添加用户
        </button>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card stats-card">
                <div class="card-body">
                    <h5 class="card-title">总用户数</h5>
                    <h2 class="text-primary" id="totalUsers">0</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stats-card">
                <div class="card-body">
                    <h5 class="card-title">平均年龄</h5>
                    <h2 class="text-success" id="avgAge">0</h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stats-card">
                <div class="card-body">
                    <h5 class="card-title">最新用户</h5>
                    <h5 class="text-info" id="latestUser">-</h5>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stats-card">
                <div class="card-body">
                    <h5 class="card-title">今日新增</h5>
                    <h2 class="text-warning" id="todayNew">0</h2>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 操作区域 -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                <i class="bi bi-plus-circle"></i> 添加用户
            </button>
            <button type="button" class="btn btn-outline-secondary" id="refreshBtn">
                <i class="bi bi-arrow-clockwise"></i> 刷新
            </button>
        </div>
        <div class="search-box">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="搜索用户..." id="searchInput">
                <button class="btn btn-outline-secondary" type="button" id="searchBtn">
                    <i class="bi bi-search"></i>
                </button>
            </div>
        </div>
    </div>
    
    <!-- 加载中提示 -->
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2">正在加载数据...</p>
    </div>
    
    <!-- 用户表格 -->
    <div class="table-container">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>头像</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>年龄</th>
                        <th>创建时间</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userTableBody">
                    <!-- 用户数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
            
            <!-- 空状态提示 -->
            <div class="empty-state" id="emptyState" style="display: none;">
                <i class="bi bi-people"></i>
                <h4>暂无用户数据</h4>
                <p>点击"添加用户"按钮创建第一个用户</p>
            </div>
        </div>
    </div>
</div>

    <!-- 添加用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        <div class="mb-3">
                            <label for="addUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="addUsername" required>
                        </div>
                        <div class="mb-3">
                            <label for="addPassword" class="form-label">密码</label>
                            <input type="password" class="form-control" id="addPassword" required>
                        </div>
                        <div class="mb-3">
                            <label for="addEmail" class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="addEmail">
                        </div>
                        <div class="mb-3">
                            <label for="addAge" class="form-label">年龄</label>
                            <input type="number" class="form-control" id="addAge">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveAddUser">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        <input type="hidden" id="editUserId">
                        <div class="mb-3">
                            <label for="editUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="editUsername" required>
                        </div>
                        <div class="mb-3">
                            <label for="editPassword" class="form-label">密码</label>
                            <input type="password" class="form-control" id="editPassword">
                        </div>
                        <div class="mb-3">
                            <label for="editEmail" class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="editEmail">
                        </div>
                        <div class="mb-3">
                            <label for="editAge" class="form-label">年龄</label>
                            <input type="number" class="form-control" id="editAge">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveEditUser">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除用户 "<span id="deleteUsername"></span>" 吗？此操作不可撤销。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteUser">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast 通知 -->
    <div class="toast-container">
        <div id="notificationToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <strong class="me-auto" id="toastTitle">通知</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body" id="toastMessage">
                操作成功
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let userIdToDelete = null;
        let allUsers = [];
        let filteredUsers = [];

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            loadUsers();
            
            // 添加用户按钮点击事件
            document.getElementById('saveAddUser').addEventListener('click', addUser);
            
            // 编辑用户按钮点击事件
            document.getElementById('saveEditUser').addEventListener('click', updateUser);
            
            // 删除用户按钮点击事件
            document.getElementById('confirmDeleteUser').addEventListener('click', deleteUser);
            
            // 刷新按钮点击事件
            document.getElementById('refreshBtn').addEventListener('click', loadUsers);
            
            // 搜索按钮点击事件
            document.getElementById('searchBtn').addEventListener('click', filterUsers);
            
            // 搜索输入框回车事件
            document.getElementById('searchInput').addEventListener('keyup', function(event) {
                if (event.key === 'Enter') {
                    filterUsers();
                }
            });
        });

        // 加载用户列表
        function loadUsers() {
            // 显示加载中提示
            document.getElementById('loadingSpinner').style.display = 'block';
            document.getElementById('userTableBody').innerHTML = '';
            document.getElementById('emptyState').style.display = 'none';
            
            fetch('/api/users')
                .then(response => response.json())
                .then(data => {
                    // 隐藏加载中提示
                    document.getElementById('loadingSpinner').style.display = 'none';
                    
                    if (data.success) {
                        allUsers = data.data;
                        filteredUsers = [...allUsers];
                        
                        // 更新统计信息
                        updateStatistics();
                        
                        // 渲染用户表格
                        renderUserTable(filteredUsers);
                    } else {
                        showToast('错误', data.message, 'danger');
                    }
                })
                .catch(error => {
                    // 隐藏加载中提示
                    document.getElementById('loadingSpinner').style.display = 'none';
                    
                    showToast('错误', '获取用户列表失败', 'danger');
                    console.error('Error:', error);
                });
        }
        
        // 更新统计信息
        function updateStatistics() {
            // 总用户数
            document.getElementById('totalUsers').textContent = allUsers.length;
            
            // 平均年龄
            if (allUsers.length > 0) {
                const usersWithAge = allUsers.filter(user => user.age);
                if (usersWithAge.length > 0) {
                    const avgAge = usersWithAge.reduce((sum, user) => sum + user.age, 0) / usersWithAge.length;
                    document.getElementById('avgAge').textContent = avgAge.toFixed(1);
                } else {
                    document.getElementById('avgAge').textContent = '-';
                }
            } else {
                document.getElementById('avgAge').textContent = '-';
            }
            
            // 最新用户
            if (allUsers.length > 0) {
                const sortedUsers = [...allUsers].sort((a, b) => 
                    new Date(b.createTime) - new Date(a.createTime));
                document.getElementById('latestUser').textContent = sortedUsers[0].username;
            } else {
                document.getElementById('latestUser').textContent = '-';
            }
            
            // 今日新增
            const today = new Date().toDateString();
            const todayNew = allUsers.filter(user => 
                user.createTime && new Date(user.createTime).toDateString() === today).length;
            document.getElementById('todayNew').textContent = todayNew;
        }
        
        // 过滤用户
        function filterUsers() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase().trim();
            
            if (searchTerm === '') {
                filteredUsers = [...allUsers];
            } else {
                filteredUsers = allUsers.filter(user => 
                    user.username.toLowerCase().includes(searchTerm) || 
                    (user.email && user.email.toLowerCase().includes(searchTerm))
                );
            }
            
            renderUserTable(filteredUsers);
        }

        // 渲染用户表格
        function renderUserTable(users) {
            const tableBody = document.getElementById('userTableBody');
            const emptyState = document.getElementById('emptyState');
            
            // 清空表格
            tableBody.innerHTML = '';
            
            if (users.length === 0) {
                // 显示空状态
                emptyState.style.display = 'block';
                return;
            }
            
            // 隐藏空状态
            emptyState.style.display = 'none';
            
            // 渲染每一行用户数据
            users.forEach(user => {
                const row = document.createElement('tr');
                
                // 创建用户头像（使用用户名首字母）
                const avatar = document.createElement('div');
                avatar.className = 'user-avatar';
                avatar.textContent = user.username.charAt(0).toUpperCase();
                
                row.innerHTML = `
                    <td>${user.id}</td>
                    <td></td>
                    <td>${user.username}</td>
                    <td>${user.email || '-'}</td>
                    <td>${user.age || '-'}</td>
                    <td>${formatDateTime(user.createTime)}</td>
                    <td>${formatDateTime(user.updateTime)}</td>
                    <td class="action-buttons">
                        <button class="btn btn-sm btn-edit edit-btn" data-id="${user.id}" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-danger delete-btn" data-id="${user.id}" data-username="${user.username}" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                `;
                
                // 添加头像到第二列
                const avatarCell = row.cells[1];
                avatarCell.appendChild(avatar);
                
                tableBody.appendChild(row);
            });
            
            // 添加编辑按钮事件监听
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    loadUserForEdit(userId);
                });
            });
            
            // 添加删除按钮事件监听
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    const username = this.getAttribute('data-username');
                    showDeleteConfirmation(userId, username);
                });
            });
        }

        // 格式化日期时间
        function formatDateTime(dateTimeString) {
            if (!dateTimeString) return '-';
            const date = new Date(dateTimeString);
            return date.toLocaleString();
        }

        // 添加用户
        function addUser() {
            const username = document.getElementById('addUsername').value;
            const password = document.getElementById('addPassword').value;
            const email = document.getElementById('addEmail').value;
            const age = document.getElementById('addAge').value;
            
            if (!username || !password) {
                showToast('错误', '用户名和密码不能为空', 'danger');
                return;
            }
            
            const user = {
                username: username,
                password: password,
                email: email,
                age: age ? parseInt(age) : null
            };
            
            fetch('/api/users', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('成功', data.message, 'success');
                    bootstrap.Modal.getInstance(document.getElementById('addUserModal')).hide();
                    document.getElementById('addUserForm').reset();
                    loadUsers();
                } else {
                    showToast('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                showToast('错误', '添加用户失败', 'danger');
                console.error('Error:', error);
            });
        }

        // 加载用户信息用于编辑
        function loadUserForEdit(userId) {
            fetch(`/api/users/${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const user = data.data;
                        document.getElementById('editUserId').value = user.id;
                        document.getElementById('editUsername').value = user.username;
                        document.getElementById('editPassword').value = '';
                        document.getElementById('editEmail').value = user.email || '';
                        document.getElementById('editAge').value = user.age || '';
                        
                        new bootstrap.Modal(document.getElementById('editUserModal')).show();
                    } else {
                        showToast('错误', data.message, 'danger');
                    }
                })
                .catch(error => {
                    showToast('错误', '获取用户信息失败', 'danger');
                    console.error('Error:', error);
                });
        }

        // 更新用户
        function updateUser() {
            const userId = document.getElementById('editUserId').value;
            const username = document.getElementById('editUsername').value;
            const password = document.getElementById('editPassword').value;
            const email = document.getElementById('editEmail').value;
            const age = document.getElementById('editAge').value;
            
            if (!username) {
                showToast('错误', '用户名不能为空', 'danger');
                return;
            }
            
            const user = {
                username: username,
                email: email,
                age: age ? parseInt(age) : null
            };
            
            // 如果密码不为空，则更新密码
            if (password) {
                user.password = password;
            }
            
            fetch(`/api/users/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('成功', data.message, 'success');
                    bootstrap.Modal.getInstance(document.getElementById('editUserModal')).hide();
                    loadUsers();
                } else {
                    showToast('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                showToast('错误', '更新用户失败', 'danger');
                console.error('Error:', error);
            });
        }

        // 显示删除确认对话框
        function showDeleteConfirmation(userId, username) {
            userIdToDelete = userId;
            document.getElementById('deleteUsername').textContent = username;
            new bootstrap.Modal(document.getElementById('deleteUserModal')).show();
        }

        // 删除用户
        function deleteUser() {
            if (!userIdToDelete) return;
            
            fetch(`/api/users/${userIdToDelete}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('成功', data.message, 'success');
                    bootstrap.Modal.getInstance(document.getElementById('deleteUserModal')).hide();
                    loadUsers();
                } else {
                    showToast('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                showToast('错误', '删除用户失败', 'danger');
                console.error('Error:', error);
            })
            .finally(() => {
                userIdToDelete = null;
            });
        }

        // 显示Toast通知
        function showToast(title, message, type = 'info') {
            const toastElement = document.getElementById('notificationToast');
            const toastTitle = document.getElementById('toastTitle');
            const toastMessage = document.getElementById('toastMessage');
            
            // 设置Toast内容
            toastTitle.textContent = title;
            toastMessage.textContent = message;
            
            // 设置Toast样式
            toastElement.className = 'toast';
            if (type === 'success') {
                toastElement.classList.add('text-bg-success');
            } else if (type === 'danger') {
                toastElement.classList.add('text-bg-danger');
            } else if (type === 'warning') {
                toastElement.classList.add('text-bg-warning');
            } else {
                toastElement.classList.add('text-bg-info');
            }
            
            // 显示Toast
            const toast = new bootstrap.Toast(toastElement);
            toast.show();
        }
    </script>
</body>
</html>